//
//  RxAlamofireUploadViewController.swift
//  iOS-RxSwift-Tutorials_Example
//
//  Created by mengru.tian on 2020/9/22.
//  Copyright © 2020 CocoaPods. All rights reserved.
//

import UIKit
import RxSwift
import RxAlamofire
import Alamofire

class RxAlamofireUploadViewController: UIViewController {

    @IBOutlet weak var progressView: UIProgressView!
    
    let disposeBag = DisposeBag()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        title = "43.结合RxAlamofire使用3：文件上传"
        view.backgroundColor = .white
        
//        test()
//        test2()
        test3()
    }
    
    // 使用文件流的形式上传文件
    func test() {
        //需要上传的文件路径
        let fileURL = Bundle.main.url(forResource: "Obervable.png", withExtension: "zip")
        //服务器路径
        let uploadURL = URL(string: "http://www.hangge.com/upload.php")!
         
        //将文件上传到服务器
        upload(fileURL!, urlRequest: try! urlRequest(.post, uploadURL))
            .subscribe(onCompleted: {
                print("上传完毕!")
            })
            .disposed(by: disposeBag)
    }
    
    // 获得上传进度
    func test2() {
        //需要上传的文件路径
        let fileURL = Bundle.main.url(forResource: "Obervable.png", withExtension: "zip")
        //服务器路径
        let uploadURL = URL(string: "http://www.hangge.com/upload.php")!
         
        //将文件上传到服务器
        upload(fileURL!, urlRequest: try! urlRequest(.post, uploadURL))
            .subscribe(onNext: { element in
                print("--- 开始上传 ---")
                element.uploadProgress(closure: { (progress) in
                    print("当前进度：\(progress.fractionCompleted)")
                    print("  已上传载：\(progress.completedUnitCount/1024)KB")
                    print("  总大小：\(progress.totalUnitCount/1024)KB")
                })
            }, onError: { error in
                print("上传失败! 失败原因：\(error)")
            }, onCompleted: {
                print("上传完毕!")
            })
            .disposed(by: disposeBag)
    }
    
    // 下面我换种写法，将进度转成可观察序列，并绑定到进度条上显示。
    func test3() {
        //需要上传的文件路径
        let fileURL = Bundle.main.url(forResource: "Obervable.png", withExtension: "zip")
        //服务器路径
        let uploadURL = URL(string: "http://www.hangge.com/upload.php")!
         
        //将文件上传到服务器
        upload(fileURL!, urlRequest: try! urlRequest(.post, uploadURL))
            .map{request in
                //返回一个关于进度的可观察序列
                Observable<Float>.create{observer in
                    request.uploadProgress(closure: { (progress) in
                        observer.onNext(Float(progress.fractionCompleted))
                        if progress.isFinished{
                            observer.onCompleted()
                        }
                    })
                    return Disposables.create()
                }
            }
            .flatMap{$0}
            .bind(to: progressView.rx.progress) //将进度绑定UIProgressView上
            .disposed(by: disposeBag)
    }
    
    // 上传 MultipartFormData 类型的文件数据（类似于网页上 Form 表单里的文件提交）
    // 上传两个文件
    func test4() {
//        //需要上传的文件
//        let fileURL1 = Bundle.main.url(forResource: "0", withExtension: "png")
//        let fileURL2 = Bundle.main.url(forResource: "1", withExtension: "png")
//
//        //服务器路径
//        let uploadURL = URL(string: "http://www.hangge.com/upload2.php")!
//
//        //将文件上传到服务器
//        upload(
//            multipartFormData: { multipartFormData in
//                multipartFormData.append(fileURL1!, withName: "file1")
//                multipartFormData.append(fileURL2!, withName: "file2")
//            },
//            to: uploadURL,
//            encodingCompletion: { encodingResult in
//                switch encodingResult {
//                case .success(let upload, _, _):
//                    upload.responseJSON { response in
//                        debugPrint(response)
//                    }
//                case .failure(let encodingError):
//                    print(encodingError)
//                }
//            })
    }
    
    // 文本参数与文件一起提交（文件除了可以使用 fileURL，还可以上传 Data 类型的文件数据）
    func test5() {
//        //字符串
//        let strData = "hangge.com".data(using: String.Encoding.utf8)
//        //数字
//        let intData = String(10).data(using: String.Encoding.utf8)
//        //文件1
//        let path = Bundle.main.url(forResource: "0", withExtension: "png")!
//        let file1Data = try! Data(contentsOf: path)
//        //文件2
//        let file2URL = Bundle.main.url(forResource: "1", withExtension: "png")
//
//        //服务器路径
//        let uploadURL = URL(string: "http://www.hangge.com/upload2.php")!
//
//        //将文件上传到服务器
//        upload(
//            multipartFormData: { multipartFormData in
//                multipartFormData.append(strData!, withName: "value1")
//                multipartFormData.append(intData!, withName: "value2")
//                multipartFormData.append(file1Data, withName: "file1",
//                                         fileName: "php.png", mimeType: "image/png")
//                multipartFormData.append(file2URL!, withName: "file2")
//            },
//            to: uploadURL,
//            encodingCompletion: { encodingResult in
//                switch encodingResult {
//                case .success(let upload, _, _):
//                    upload.responseJSON { response in
//                        debugPrint(response)
//                    }
//                case .failure(let encodingError):
//                    print(encodingError)
//                }
//            })
    }
}
